<template>
  <el-tabs v-model="activeName">
    <el-tab-pane label="预约列表" name="list" >
<!--      <el-button type="primary" style="margin-bottom: 16px;" @click="dialogVisible = true">-->
<!--        新增预约-->
<!--      </el-button>-->
      <el-button type="primary" style="margin-bottom: 16px;" @click="exportVisible = true">
        导出数据
      </el-button>

      <el-table :data="reservations" style="width: 100%" border >
        <el-table-column label="序号" prop="id" />
        <el-table-column label="姓名" prop="realName" />
<!--        <el-table-column label="类型" prop="roomSubTypeName" />-->
        <el-table-column label="仪器名称" prop="instrumentName" />
<!--        <el-table-column label="隔间号码" prop="cubicleNumber" />-->
        <el-table-column label="预约日期" prop="reservationDate" />
        <el-table-column label="开始时间" prop="startTime" />
        <el-table-column label="结束时间" prop="endTime" />
        <el-table-column label="签到时间" prop="clockInTime"/>
        <el-table-column label="签退时间" prop="clockOutTime"/>
        <el-table-column label="状态" prop="statusName" />
        <el-table-column label="操作" width="120">
          <template #header>
            <el-input
                v-model="search"
                @input="handleSearch"
                size="small"
                placeholder="通过姓名搜索"
            />
          </template>
          <template #default="scope">

          </template>
        </el-table-column>
      </el-table>


      <el-pagination
          v-model:current-page="page"
          :page-size="pageSize"
          :total="total"
          @current-change="handlePageChange"
          layout="total, prev, pager, next"
          background
          style="margin-top: 16px"
      />
    </el-tab-pane>

    <el-tab-pane label="待审核列表" name="list2">
      <el-table :data="reviewReservations" style="width: 100%" border>
        <el-table-column label="序号" prop="id" />
        <el-table-column label="姓名" prop="realName" />
        <el-table-column label="仪器名称" prop="instrumentName" />
        <el-table-column label="预约日期" prop="reservationDate" />
        <el-table-column label="开始时间" prop="startTime" />
        <el-table-column label="结束时间" prop="endTime" />
        <el-table-column label="状态" prop="statusName" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" type="success" @click="approveReservation(scope.row)">
              通过
            </el-button>
            <el-button size="small" type="danger" @click="rejectReservation(scope.row)">
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          v-model:current-page="reviewPage"
          :page-size="reviewPageSize"
          :total="reviewTotal"
          @current-change="handleReviewPageChange"
          layout="total, prev, pager, next"
          background
          style="margin-top: 16px"
      />
    </el-tab-pane>
  </el-tabs>

  <el-dialog v-model="dialogVisible" title="新增预约" width="500px">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="用户ID" prop="userId">
        <el-input v-model="form.userId" />
      </el-form-item>
      <el-form-item label="房间ID" prop="roomId">
        <el-input v-model="form.roomId" />
      </el-form-item>
      <el-form-item label="隔间号" prop="cubicleNumber">
        <el-input-number v-model="form.cubicleNumber" :min="1" />
      </el-form-item>
      <el-form-item label="预约日期" prop="date">
        <el-date-picker v-model="form.date" type="date" />
      </el-form-item>
      <el-form-item label="时间段ID" prop="timeSlotId">
        <el-input v-model="form.timeSlotId" />
      </el-form-item>
      <el-form-item label="扣除积分" prop="points">
        <el-input-number v-model="form.points" :min="0" />
      </el-form-item>
      <el-form-item label="审核人ID" prop="reviewerId">
        <el-input v-model="form.reviewerId" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">提交</el-button>
    </template>
  </el-dialog>
  <ExportDialog
      v-model="exportVisible"
      :type="exportType"
      @export="onExport"
  />
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getReservations,
  addReservation,
  getReservationsByNotReview,
  approveReservationApi,
  rejectReservationApi
} from '../utils/reservationApi.js'
import ExportDialog from "@/apps/admin/components/ExportDialog.vue";
import {debounce} from "lodash";
const exportVisible = ref(false)
const exportType = ref('INSTRUMENT')
const search = ref("")
const onExport = (data) => {
  console.log('导出参数：', data)

}
const activeName = ref("list")

const reservations = ref([])
const page = ref(1)
const pageSize = 10
const total = ref(0)

const reviewReservations = ref([])
const reviewPage = ref(1)
const reviewPageSize = 10
const reviewTotal = ref(0)

const dialogVisible = ref(false)
const formRef = ref(null)

const form = reactive({
  userId: '',
  roomId: '',
  cubicleNumber: 1,
  date: '',
  timeSlotId: '',
  points: 0,
  reviewerId: ''
})

const rules = {
  userId: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
  roomId: [{ required: true, message: '请输入房间ID', trigger: 'blur' }],
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  timeSlotId: [{ required: true, message: '请输入时间段ID', trigger: 'blur' }],
  reviewerId: [{ required: true, message: '请输入审核人ID', trigger: 'blur' }]
}
// 响应 data.{records total}
const loadReservations = async () => {
  const res = await getReservations("INSTRUMENT", page.value, pageSize, search.value)
  reservations.value = res.data.records || res.data
  total.value = res.data.total || reservations.value.length
}

const loadReviewReservations = async () => {
  const res = await getReservationsByNotReview("INSTRUMENT", reviewPage.value, reviewPageSize)
  reviewReservations.value = res.data.records || res.data
  reviewTotal.value = res.data.total || reviewReservations.value.length
}

const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await addReservation(form)
        ElMessage.success('新增预约成功')
        dialogVisible.value = false
        await loadReservations()
      } catch (e) {
        ElMessage.error('新增失败：' + (e.message || '未知错误'))
      }
    }
  })
}

const approveReservation = (reservation) => {
  ElMessageBox.confirm(`确定通过预定ID ${reservation.id} 的审核吗？`, '确认通过', {
    type: 'warning',
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  })
      .then(() => approveReservationApi({ reservationId: reservation.id }))
      .then(() => {
        ElMessage.success('审核通过')
        loadReservations()
        loadReviewReservations()
      })
      .catch(() => {})
}

const rejectReservation = (reservation) => {
  ElMessageBox.confirm(`确定拒绝预定ID ${reservation.id} 的审核吗？`, '确认拒绝', {
    type: 'warning',
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  })
      .then(() => rejectReservationApi({ reservationId: reservation.id }))
      .then(() => {
        ElMessage.success('已拒绝该预定')
        loadReservations()
        loadReviewReservations()
      })
      .catch(() => {})
}


const handlePageChange = (newPage) => {
  page.value = newPage
  loadReservations()
}

const handleReviewPageChange = (newPage) => {
  reviewPage.value = newPage
  loadReviewReservations()
}

// 防抖搜索函数
const handleSearch = debounce(() => {
  page.value = 1
  loadReservations()
}, 300)

// 初始加载
loadReservations()
loadReviewReservations()
</script>
